package com.ysxsoft.wdg.ui.activity.login;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.socks.library.KLog;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.UserInfoBean;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.bean.response.WxCheckResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.MainActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.delayaction.SingleCall;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import pl.droidsonroids.gif.GifImageView;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.REGISTER_OK;

public class LoginActivity extends BaseActivity {


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.et_user)
    EditText etUser;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    @BindView(R.id.et_psw)
    EditText etPsw; @BindView(R.id.loading)
    GifImageView loading;
    private int jump = 0;
    UMShareAPI mShareAPI;
    private String open_id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        EventBus.getDefault().register(this);

        jump = getIntent().getIntExtra("jump", 0);
        mShareAPI = UMShareAPI.get(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void setListener() {
    }

    @OnClick({R.id.btn_login, R.id.tv_register, R.id.tv_forget, R.id.iv_wx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                String user = etUser.getText().toString().trim();
                String pse = etPsw.getText().toString().trim();

                if (TextUtils.isEmpty(user) || TextUtils.isEmpty(pse)) {
                    ToastUtils.showToast("账号或密码不能为空");
                    return;
                }

                mApiHelper.postLogin(user, pse, JPushInterface.getRegistrationID(this), new Observer<BaseBean<UserInfoBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseBean<UserInfoBean> baseBean) {
                        ToastUtils.showToast(baseBean.getMs());
                        if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                            try {
                                SingleCall.getInstance().doCall();
                            } catch (Exception e) {
                                e.printStackTrace();
                                KLog.e(e.toString());
                            }

                            SharePrefUtils.saveUserId(baseBean.getData().getId());
                            SharePrefUtils.saveUserCode(baseBean.getData().getCode());

                            if (jump == 0) {
                                MainActivity.start(mContext);
                            }
                            finish();
                        } else {
                            ToastUtils.showToast(baseBean.getMs());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });

                break;
            case R.id.tv_register:
                RegisterActivity.start(this);
                break;
            case R.id.tv_forget:
                ForgetPswActivity.start(this, 0);
                break;
            case R.id.iv_wx:
                wechartLogin();
                break;
        }
    }

    @Subscribe
    public void getEvent(CommentEvent event) {
        int code = event.getCode();
        if (code == REGISTER_OK) {
            etUser.setText(event.getMs());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        ViewUtils.closeKeyboard(this);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (jump == 0) {
            MainActivity.start(mContext);
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 微信登录
     */
    private void wechartLogin() {
        if (mShareAPI.isInstall(LoginActivity.this, SHARE_MEDIA.WEIXIN)) {
            Log.e("tag", "获取信息start");
            mShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);
        } else {
            Toast.makeText(this, "请安装微信！", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取资料
     */
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            Log.e("tag", new Gson().toJson(map));
            if (map != null) {
                open_id = map.get("openid");
                String screen_name = map.get("screen_name");
                String profile_image_url = map.get("profile_image_url");
                Log.e("tag", "开始登陆");
                wxCheck(screen_name, open_id, profile_image_url);
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Log.e("tag", "获取信息onError" + t.getMessage());
//            Toast.makeText(LoginActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Log.e("tag", "获取信息onCancel");
//            Toast.makeText(LoginActivity.this, "取消获取用户信息", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStart(SHARE_MEDIA share_media) {
            Log.e("tag", "获取信息onStart");
        }
    };

    private void wxCheck(String screen_name, String open_id, String profile_image_url) {
//        multStatusView.showLoading();
        loading.setVisibility(View.VISIBLE);
        OkHttpUtils.post()
                .url(UrlHost.WX_CHECK)
                .addParams("openid", open_id)
                .addParams("a_cid", JPushInterface.getRegistrationID(LoginActivity.this))
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
//                    multStatusView.showContent();
                    loading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onResponse(String response, int id) {
//                multStatusView.showContent();
                loading.setVisibility(View.GONE);
                if (response != null) {
                    WxCheckResponse bean = JsonUtils.parseByGson(response, WxCheckResponse.class);
                    if (bean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(bean.getCode())) {
                        WxCheckResponse.DataBean response1=bean.getData();
                        if(response1!=null){
                            String c=response1.getCode();
                            int uid=response1.getUid();
                            SharePrefUtils.saveUserId(uid+"");
                            SharePrefUtils.saveUserCode(c);
                            MainActivity.start(LoginActivity.this);
                        }
                    } else if (CallbackCode.ERROR.equals(bean.getCode())) {
                        ToastUtils.showToast(bean.getMs());
                        //请绑定手机号
                        BindPhoneActivity.start(LoginActivity.this, open_id, screen_name, profile_image_url);
                    }
                } else {
                }
            }
        });
    }

    private void login(String open_id) {
//        multStatusView.showLoading();
        loading.setVisibility(View.VISIBLE);
        OkHttpUtils.post()
                .url(UrlHost.WX_CHECK)
                .addParams("openid", open_id)
                .addParams("a_cid", JPushInterface.getRegistrationID(LoginActivity.this))
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    loading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                loading.setVisibility(View.GONE);
                if (response != null) {
                    WxCheckResponse bean = JsonUtils.parseByGson(response, WxCheckResponse.class);
                    if (bean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(bean.getCode())) {
                        WxCheckResponse.DataBean response1=bean.getData();
                        if(response1!=null){
                            String c=response1.getCode();
                            int uid=response1.getUid();
                            SharePrefUtils.saveUserId(uid+"");
                            SharePrefUtils.saveUserCode(c);
                            MainActivity.start(LoginActivity.this);
                        }
                    } else if (CallbackCode.ERROR.equals(bean.getCode())) {
                        ToastUtils.showToast(bean.getMs());
                    }
                } else {
                }
            }
        });
    }

}
